package game;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

import server.Client;

public class Network {
	public final String verision = "1";

	private final int CLIENT_CONNECT = 1;
	public final int CLIENT_DISCONNECT = 2;
	public final int CLIENT_SETNAME = 3;
	public final int CLIENT_POS = 4; // (will be used later)

	public final String DEFAULT_REGEX = "|";

	private boolean run = false;
	private Socket server;
	private PrintWriter out;
	private BufferedReader in;
	private String ip;
	private int port;
	private String name;
	
	public Network(String name, String ip, int port) {
		this.name = name;
		this.ip = ip;
		this.port = port;
		
	}
	
	public void sendPos(float x, float y) {
		send(CLIENT_POS + DEFAULT_REGEX + x + DEFAULT_REGEX + y);
	}
	
	private void send(String data) {
		out.println(data);
	}
	
	private void listen() {
		new Thread() {
			public void run() {
				while (run) {
					try {
						String data;
						while ((data = in.readLine()) != null) {
							process(data);
						}
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}
		}.start();
	}
	
	public void process(String s) {
		String data[] = s.split(DEFAULT_REGEX);
		int id = -1;
		try {
			id = Integer.parseInt(data[0]);
		} catch (Exception e) {
			System.err.println("Invalid packet id: " + id);
			return;
		}
		
		String clientName;

		switch (id) {
		case CLIENT_CONNECT:
			clientName = data[1];
			
			break;
		case CLIENT_POS:
			clientName = data[1];
			float x = Float.parseFloat(data[2]);
			float y = Float.parseFloat(data[3]);
			
			break;
		}

	}
	
	public void connect() {
		run = true;
		try {
			server = new Socket(ip, port);
			in = new BufferedReader(new InputStreamReader(server.getInputStream()));
			out = new PrintWriter(server.getOutputStream());
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		send(CLIENT_SETNAME + DEFAULT_REGEX + name);
		listen();
	}
	
	public void disconnect() {
		run = false;
		try {
			in.close();
			out.close();
			server.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
